package com.stedu.mall.userservice.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.Collect;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.CollectService;
import com.stedu.mall.common.service.GoodsService;
import com.stedu.mall.userservice.mapper.CollectMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectMapper collectMapper;
    @DubboReference
    private GoodsService goodsService;
    @Override
    public boolean insert(Collect collect) throws SteduException {
        if (collectMapper.selectByGoodsIdAndUserId(collect.getGoodsId(), collect.getUserId()) != null){
            throw new SteduException("商品无法重复收藏");
        }
        //添加

        return collectMapper.insert(collect) == 1;
    }

    @Override
    public boolean delete(Integer id, Integer userid) throws SteduException {
        //收藏是否存在
        Collect collect = collectMapper.selectById(id);
        if(collect == null){
            throw  new SteduException("该收藏不存在，无法取消收藏");
        }
        //判断这个收藏是否属于当前用户
        if(!collect.getUserId().equals(userid)){
            throw  new SteduException("你不是本用户无法进行收藏操作");
        }
        //取消收藏
        return collectMapper.delete(id) == 1;
    }

    @Override
    public Collect selectByGoodsIdAndUserId(Integer goodsId, Integer userId) {
        return collectMapper.selectByGoodsIdAndUserId(goodsId, userId);
    }

    @Override
    public PageInfo<Collect> selectBypage(Integer userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Collect> collectList = collectMapper.selectByUserId(userId);
        collectList.stream()
                .forEach(c -> {c.setGoods(goodsService.selectById(c.getGoodsId()));});
        PageInfo<Collect> pageInfo= new PageInfo<>(collectList);
        return pageInfo;
    }
}
